package com.block.datapush.service.apipush;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.QianManDaiUtil;
import com.block.datapush.service.apipush.utils.XieWanGaoUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 钱满贷
 */
@Service
public class QianManDaiApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);


        String queryUrl = pushApiKeyParam.getCheckUrl();

        String channelId = pushApiKeyParam.getApiCode();
        String secret = pushApiKeyParam.getApiSecret();
        String mobileMd5 = memberSourceInfo.getMobileMd5();

        String sign = SecureUtil.md5(channelId + "&" + mobileMd5 + "&" + secret).toLowerCase();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channelId", channelId);
        paramMap.put("sign", sign);
        paramMap.put("mobileMd5", mobileMd5);


        log.info("【钱满贷】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【钱满贷】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);

        int code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0")) {
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();



        long time = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(time);
        String dates = sdf.format(date);

        String city = memberSourceInfo.getCity();
        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("hide", "1");
        bizMap.put("fallbackContent",orderNo);
        bizMap.put("osType", "1");
        bizMap.put("source", "臻享分期");
        bizMap.put("city", city);
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? 1 : 0);
        bizMap.put("idNo", memberSourceInfo.getIdcard());
        bizMap.put("subChannelId", pushApiKeyParam.getApiKey());
        bizMap.put("subChannelName", "臻享分期api和crm统计");
//       bizMap.put("subChannelName", "臻享分期测试");
        bizMap.put("salaryOfMonth", QianManDaiUtil.getshouru(memberSourceInfo.getShouru()));
        bizMap.put("education", QianManDaiUtil.getxueli(memberSourceInfo.getXueli()));
        bizMap.put("profession", QianManDaiUtil.getjob(memberSourceInfo.getGongzuo()));
        bizMap.put("workTime", 12);
        bizMap.put("paymentForm", 3);
        bizMap.put("commercialInsurance", QianManDaiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("house", QianManDaiUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("car", QianManDaiUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("carType", 0);
        bizMap.put("carOwnership", 0);
        bizMap.put("carState", 0);
        bizMap.put("carYear", 0);
        bizMap.put("carPrice", 0);
        bizMap.put("socialSecurity", QianManDaiUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("accumulationFound", QianManDaiUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("creditCard", 0);
        bizMap.put("weili", 0);
        bizMap.put("zhima", QianManDaiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("loanAmount", QianManDaiUtil.getLoanAount(memberSourceInfo.getLoanAmount()));
        bizMap.put("loanTime", QianManDaiUtil.getLoanTime(memberSourceInfo.getLoanTime()));
        bizMap.put("purpose", QianManDaiUtil.getYongtu(memberSourceInfo.getYongtu()));
        bizMap.put("overdue", QianManDaiUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("baiTiao", QianManDaiUtil.getbaitiao(memberSourceInfo.getBaitiao()));
        bizMap.put("huaBei", QianManDaiUtil.gethuabei(memberSourceInfo.getHuabei()));
        bizMap.put("businessName", "无");
        bizMap.put("businessTime", "0");
        bizMap.put("businessLocation", "无");
        bizMap.put("createTime", dates);


        String nonCritical = memberSourceInfo.getRealname() + "&" + memberSourceInfo.getMobile();

        String base64 = SecureUtil.aes(pushApiKeyParam.getApiSecret().getBytes()).encryptBase64(nonCritical);
        bizMap.put("nonCritical",base64);


        String nonceStr = RandomUtil.randomString(16);


        String channelId = pushApiKeyParam.getApiCode();
        String secret = pushApiKeyParam.getApiSecret();
        String sign = channelId + "&&" + nonceStr + "&&" + JSON.toJSONString(bizMap) + "=" + secret;

        String signMd5 = SecureUtil.md5(sign).toLowerCase();


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channelId", channelId);
        paramMap.put("sign", signMd5);
        paramMap.put("method", "/v1/api");
        paramMap.put("nonceStr", nonceStr);
        paramMap.put("mobileText", memberSourceInfo.getMobileMd5());
        paramMap.put("data", JSON.toJSONString(bizMap));


        log.info("【钱满贷】导单开始【queryUrl】{}【paramMap】{}【bizMap】{}", requestUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【钱满贷】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);

        int code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");
        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if ( StrUtil.equals(String.valueOf(code), "0")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }


    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }


}
